<template>
  <div class="styleList">
    <accessTable
      v-if="!isShowPage"
      @addFun="addFun"
      @search="search"
      @sizeChange="sizeChange"
      @pageBack="pageBack"
      @currentChangeFun="currentChangeFun"
      :isAdd="limitArr.indexOf('sdk_style_list_insert') > -1"
      :quickSearchForm="quickSearchForm"
      :tableHeader="tableHeader"
      :tablePages="tablePages"
      :tableData="tableData">
    </accessTable>
    <styleAddOrEdit ref="styleAddOrEditRef" class="addOrEditBox" v-show="isShowPage" :titleArr="titleArr" @pageBack="pageBack" @saveFun="saveFun"></styleAddOrEdit>
  </div>
</template>
<script lang='ts'>
import { Component, Vue, Ref } from 'vue-property-decorator'
import { deepClone } from '@/utils/common'
import { CommonModule } from '@/store/modules/common'
import styleAddOrEdit from '@/views/config/webchat/channel/sdk/styleAddOrEdit.vue'
import accessTable from '@/views/config/webchat/channel/base/accessTable.vue'
import { channelConfigMoudle } from '@/store/modules/config/channel/index'
import { checkPermission } from '@/utils/directive'
interface InterStatus {
  [x: string]: any
  status: 'enable' | 'disable'
}
interface TableItem {
  _id: string
}
@Component({
  name: 'sdkStyleConfig',
  components: { accessTable, styleAddOrEdit }
})
export default class SdkStyleConfig extends Vue {
  @Ref() private readonly styleAddOrEditRef !: styleAddOrEdit
  private $bus: any
  private $confirm: any
  private $store: any
  private $deleteCache: any
  private $getCache: any
  private tablePages = {
    current: 1,
    pageSize: 10,
    total: 0
  }

  private limitArr: any = [] // 权限

  private isShowPage = false // 是否展示table

  private titleArr = ['样式设置', '添加样式'] // 面包屑

  private channelData = [] // 渠道列表数据

  private quickSearchForm: any = {} // 快捷搜索

  private tableHeader: any = [ // table表头
    { label: '样式名称', prop: 'name' },
    { label: 'SDK名称', prop: 'channelName', isSort: true, width: 260 },
    { label: '创建人', prop: 'createName' },
    { label: '最后更新时间', prop: 'updateTime', isSort: true }
  ]

  private tableData = [] // table数据

  private queryTableList (addSuccess?: any) { // 获取table数据
    if (addSuccess) { // 新增回到第一页
      this.tablePages.current = 1
    }
    const sendData = { page: this.tablePages.current, limit: this.tablePages.pageSize, query: { ...this.quickSearchForm.form } }
    const actionData = { url: '/im-sdk/action/config/sdkCssTmp/list', method: 'POST', data: { ...sendData } }
    channelConfigMoudle.channelCommonAction(actionData).then(res => {
      if (res.data.list) {
        const list = res.data.list || []
        if (list.length === 0) {
          const page = Math.ceil(res.count / this.tablePages.pageSize)
          if (!res.count) { // 第一页且count为0是不再发请求（!res.count，以防后端没有返回count,直接死循环）
            this.tablePages.current = 1
          } else { // 删除到最后一个回到上一页
            this.tablePages.current = page
            this.queryTableList()
            return false
          }
        }
        if (list.length > 0) {
          list.forEach(item => {
            if (item.channelIds && item.channelIds.length > 0) {
              let name = ''
              item.channelIds.forEach(channelItem => {
                const channelItemObj: any = deepClone(CommonModule.publicCache.channelListObj[channelItem])
                name += (channelItemObj && channelItemObj.name) ? channelItemObj.name + ' ' : ''
              })
              item.channelName = name // 渠道名称
            } else {
              item.channelName = '--'
            }
            const agentObj = deepClone(CommonModule.publicCache.userListObj)[item.createUser]
            item.createName = agentObj ? agentObj.name : '--' // 创建人
          })
        }
        this.tableData = res.data.list
        this.tablePages.total = res.data.count || 0
      }
    })
  }

  private editFun (row: any) { // 样式编辑事件
    this.titleArr = ['样式设置', '编辑样式']
    this.isShowPage = true
    this.$nextTick(() => {
      this.styleAddOrEditRef.styleName = row.name
      this.styleAddOrEditRef.styleId = row._id
      this.$bus.$emit('sdkEdit', row.sessionWindow || {})
    })
  }

  private pageBack () { // 样式列表返回
    (this as any).$confirm('您没有进行保存操作, 确定离开页面吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      closeOnClickModal: false
    }).then(() => {
      this.isShowPage = false
    })
  }

  private addFun () { // 新增事件
    this.isShowPage = true
    this.$nextTick(() => {
      this.styleAddOrEditRef.styleName = ''
      this.$bus.$emit('sdkEdit')
      this.styleAddOrEditRef.styleId = ''
    })
  }

  private delFun (row: TableItem) { // 删除样式事件
    const sendData = { url: '/im-sdk/action/config/sdkCssTmp/delete', method: 'POST', data: { _id: row._id } }
    this.$confirm('确定要删除该样式吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      channelConfigMoudle.channelCommonAction(sendData).then(res => {
        if (res) {
          (this as any).$message.success('删除样式成功')
          this.$deleteCache('sdkCssList', '_id', row._id, true) // 删除样式缓存
          this.queryTableList()
        }
      })
    })
  }

  private search () { // 搜索
    this.tablePages.current = 1
    this.queryTableList()
  }

  private saveFun (data: TableItem) { // 保存事件
    this.isShowPage = false
    this.queryTableList(data._id === '' ? 'add' : null)
  }

  private sizeChange (size: number) {
    this.tablePages.pageSize = size
    this.queryTableList()
  }

  private currentChangeFun (page: number) {
    this.tablePages.current = page
    this.queryTableList()
  }

  private mounted () {
    this.$bus.$on('styleCancelFun', () => {
      this.pageBack()
    })
    this.channelData = this.$store.state.common.publicCache.channelList
    this.quickSearchForm = {
      form: {
        name: '',
        channelIds: []
      },
      advSearchOptions: [
        { label: '样式名称', inputType: 'input', placeholder: '请输入样式名称', name: 'name', clearable: true }
      ]
    }
    this.$getCache('/im-center/action/webchat/channelCache', ['channelList'], true).then((data: any) => { // 获取渠道列表，样式列表缓存
      this.queryTableList()
    })
    let handlers: any = []
    this.limitArr = this.$store.state.common.session.user.functions
    if (checkPermission(null, { value: ['sdk_style_list_edit'] })) { // 编辑权限
      handlers.push({ name: '编辑', handleFn: (scope: any) => this.editFun(scope.row) })
    }
    if (checkPermission(null, { value: ['sdk_style_list_delete'] })) { // 删除权限
      handlers = [...handlers,
        ...[
          { name: '删除', className: 'danger', handleFn: (scope: any) => this.delFun(scope.row) }
        ]
      ]
    }
    this.tableHeader.push({ label: '操作', width: 100, handlers })
  }
}
</script>
<style lang="stylus" scoped>
  .styleList
    height 100%
    .addOrEditBox
      position absolute
      width 100%
      height 100%
      left 0
      top 0
      z-index 100
      background #f3f5f7
</style>
